package edu.gyu.myshop.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.gyu.myshop.model.*;
import edu.gyu.myshop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import java.lang.management.ManagementFactory;
import java.util.stream.Collectors;

import com.sun.management.OperatingSystemMXBean;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class AdminUserController implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private GoodstypeService goodstypeService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    MyuserService myuserService;
    @Autowired
    UserAddressService userAddressService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    MyorderService myorderService;
    @Autowired
    TrackingNumbersService trackingNumberService;

    @RequestMapping("/admin/login")
    public String getadmin() {
        return "pages/login";
    }


    @PostMapping("/admin/login")
    public String Postadmin(Myuser myuser, HttpServletRequest request) {
        if (userAddressService.adminLogin(myuser, request)) {
            return "redirect:/admin/index";
        }
        return "pages/login";
    }

    @RequestMapping("/admin/index")
    public String getindex(HttpServletRequest request, HttpSession session,
                           @RequestParam(value = "page", defaultValue = "1") int page,
                           @RequestParam(value = "size", defaultValue = "5") int size) {
        // 从Session中获取用户名
        String loginUser = userAddressService.getLoginUser(request);
        session.setAttribute("username", loginUser);

        //全部用户
        int userAll = userAddressService.getUserAll();
        //今日注册用户
        int todayRegisterUser = userAddressService.getTodayRegisterUser();
        //全部订单数量
        int orderAll = userAddressService.getOrderAll();
        //今日订单数量
        int todayOrder = userAddressService.getTodayOrder();
        // 获取需要处理的订单信息 已经支付未发货
        IPage<OrderDetail> orderPage = userAddressService.listOrder(page, size);
        // 设置分页相关属性
        long totalPages = orderPage.getPages();
        long currentPage = orderPage.getCurrent();
        long totalRecords = orderPage.getTotal();
        request.setAttribute("orderPage", orderPage);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalRecords", totalRecords);
        request.setAttribute("orderPage", orderPage);
        request.setAttribute("userAll", userAll);
        request.setAttribute("todayRegisterUser", todayRegisterUser);
        request.setAttribute("orderAll", orderAll);
        request.setAttribute("todayOrder", todayOrder);
        return "pages/index";
    }

    @RequestMapping("/admin/logout")
    public String logout(HttpSession session, HttpServletRequest request) {
        request.setAttribute("msg", "退出登录成功！");
        session.invalidate();
        return "pages/login";
    }

    @RequestMapping("/admin/userList")
    public String userList(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int page,
                           @RequestParam(value = "size", defaultValue = "5") int size) {
        IPage<Myuser> myuserIPage = userAddressService.listUser(page, size);
        // 设置分页相关属性
        long totalPages = myuserIPage.getPages();
        long currentPage = myuserIPage.getCurrent();
        long totalRecords = myuserIPage.getTotal();
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalRecords", totalRecords);
        request.setAttribute("myuserIPage", myuserIPage);
        return "pages/userList";
    }

    @RequestMapping("/admin/postAddUser") //添加用户 post
    public String postAddUser(Myuser myuser, HttpServletRequest request) {
        userAddressService.postAddUser(myuser, request);
        return "pages/useradd";
    }

    @RequestMapping("/admin/useradd")  //返回添加用户的界面
    public String userAdd() {
        return "pages/useradd";
    }

    @GetMapping("/admin/userupdate/{id}")  //返回修改用户的界面
    public String userUpdate(@PathVariable("id") int id, HttpServletRequest request) {
        Myuser user = myuserService.getById(id);
        request.setAttribute("user", user);
        return "pages/userupdate";
    }

    @RequestMapping("/admin/userUpdatepost")  //修改用户处理
    public String userUpdatepost(Myuser myuser, HttpServletRequest request) {
        boolean userUpdate = userAddressService.userUpdate(myuser, request);
        if (userUpdate) {
            request.setAttribute("msg2", "修改成功");
            return "redirect:/admin/userList";
        }
        request.setAttribute("msg2", "修改失败,用户名重复");
        return "pages/userupdate";
    }

    @RequestMapping("/admin/**")  //返回404
    public String return404() {
        return "pages/404";
    }

    @GetMapping("/admin/userdetail/{id}")
    public String userDetail(@PathVariable("id") int id, Model model) {
        Myuser user = myuserService.getById(id);
        List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getUserid, id).list();

        list.forEach(orderDetail -> {
            orderDetail.setProductName(goodsService.getById(orderDetail.getGoodsid()).getName());
            orderDetail.setStatus(String.valueOf(myorderService.getById(orderDetail.getOrderid()).getStatus()));
        });

        model.addAttribute("user", user);
        model.addAttribute("orders", list);
        return "pages/userdetail";
    }

    @RequestMapping("/admin/userdelete/{id}")
    public String userDelete(@PathVariable("id") int id, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        myuserService.removeById(id);
        redirectAttributes.addFlashAttribute("msg2", "删除成功");
        return "redirect:/admin/userList";
    }


    @RequestMapping("/admin/orderList")
    public String orderList(@RequestParam(value = "page", defaultValue = "1") int page,
                            @RequestParam(value = "size", defaultValue = "10") int size, Model model) {
        IPage<OrderDetail> orderPage = userAddressService.listOrderAll(page, size);
        long totalPages = orderPage.getPages();
        long currentPage = orderPage.getCurrent();
        long totalRecords = orderPage.getTotal();
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("totalRecords", totalRecords);
        model.addAttribute("orderPage", orderPage);
        return "pages/orderList";
    }


    @RequestMapping("/admin/orderList_Delivery")  //待发货订单
    public String orderList_Delivery(@RequestParam(value = "page", defaultValue = "1") int page,
                                     @RequestParam(value = "size", defaultValue = "10") int size, Model model) {
        IPage<OrderDetail> orderPage = userAddressService.listOrderAll_Delivery(page, size);
        long totalPages = orderPage.getPages();
        long currentPage = orderPage.getCurrent();
        long totalRecords = orderPage.getTotal();
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("totalRecords", totalRecords);
        model.addAttribute("orderPage", orderPage);
        // 将过滤后的订单列表传递给视图或其他处理
        model.addAttribute("orderPage", orderPage);
        return "pages/orderList_Delivery";
    }

    @RequestMapping("/admin/orderList_Receive")  //待收货
    public String orderList_Receive(@RequestParam(value = "page", defaultValue = "1") int page,
                                    @RequestParam(value = "size", defaultValue = "10") int size, Model model) {
        IPage<OrderDetail> orderPage = userAddressService.listOrderAll_Receive(page, size);
        System.out.println(orderPage.getPages());
        long totalPages = orderPage.getPages();
        long currentPage = orderPage.getCurrent();
        long totalRecords = orderPage.getTotal();
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("totalRecords", totalRecords);
        model.addAttribute("orderPage", orderPage);
        // 将过滤后的订单列表传递给视图或其他处理
        model.addAttribute("orderPage", orderPage);
        return "pages/orderList_Receive";
    }

    @RequestMapping("/admin/orderList_Complete")  //已经完成
    public String orderList_Complete(@RequestParam(value = "page", defaultValue = "1") int page,
                                     @RequestParam(value = "size", defaultValue = "10") int size, Model model) {
        IPage<OrderDetail> orderPage = userAddressService.listOrderAll_Complete(page, size);
        long totalPages = orderPage.getPages();
        long currentPage = orderPage.getCurrent();
        long totalRecords = orderPage.getTotal();
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("totalRecords", totalRecords);
        model.addAttribute("orderPage", orderPage);
        // 将过滤后的订单列表传递给视图或其他处理
        model.addAttribute("orderPage", orderPage);
        return "pages/orderList_Complete";
    }


    @RequestMapping("/admin/orderdetail/{id}")
    public String orderDetail(@PathVariable("id") int id, Model model) {
        OrderDetail orderDetail = userAddressService.getOrderDetail(id);
        model.addAttribute("orderDetail", orderDetail);
        return "pages/orderdetail";
    }


    @RequestMapping("/admin/orderdelete/{id}")
    public String orderDelete(@PathVariable("id") int id, RedirectAttributes redirectAttributes) {
        OrderDetail orderDetail = orderDetailService.lambdaQuery().eq(OrderDetail::getId, id).one();
        System.out.println(orderDetail);
        myorderService.removeById(orderDetail.getOrderid());
        orderDetailService.removeById(id);
        redirectAttributes.addFlashAttribute("msg2", "删除成功");
        return "redirect:/admin/orderList";
    }

    @RequestMapping("/admin/system")
    public String systemSettings(Model model) {
        // 获取服务器状况
        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

        // 获取CPU使用率
        double cpuUsage = osBean.getSystemCpuLoad() * 100;
        // 获取内存使用情况
        double memoryUsage = (osBean.getTotalPhysicalMemorySize() - osBean.getFreePhysicalMemorySize()) * 100.0 / osBean.getTotalPhysicalMemorySize();

        // 获取磁盘使用情况
        File diskPartition = new File("/");
        double diskUsage = (diskPartition.getTotalSpace() - diskPartition.getFreeSpace()) * 100.0 / diskPartition.getTotalSpace();

        // 获取系统启动时间
        long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
        String systemUptime = String.format("%d天 %d小时 %d分钟",
                TimeUnit.MILLISECONDS.toDays(uptime),
                TimeUnit.MILLISECONDS.toHours(uptime) % 24,
                TimeUnit.MILLISECONDS.toMinutes(uptime) % 60);

        // 将服务器状况添加到模型
        model.addAttribute("cpuUsage", String.format("%.2f", cpuUsage));
        model.addAttribute("memoryUsage", String.format("%.2f", memoryUsage));
        model.addAttribute("diskUsage", String.format("%.2f", diskUsage));
        model.addAttribute("systemUptime", systemUptime);

        return "/pages/system";
    }

    @RequestMapping("/admin/updatePassword")
    public String updatePassword(@RequestParam("oldPassword") String oldPassword,
                                 @RequestParam("newPassword") String newPassword,
                                 @RequestParam("confirmPassword") String confirmPassword,
                                 HttpSession session,
                                 RedirectAttributes redirectAttributes) {
        if (!newPassword.equals(confirmPassword)) {
            redirectAttributes.addFlashAttribute("msg5", "新密码和确认密码不匹配");
            return "redirect:/admin/system";
        }

        boolean isUpdated = userAddressService.updatePassword(session, oldPassword, newPassword);
        if (isUpdated) {
            redirectAttributes.addFlashAttribute("msg5", "密码更新成功");
        } else {
            redirectAttributes.addFlashAttribute("msg5", "旧密码不正确");
        }
        return "redirect:/admin/system";
    }

    @RequestMapping("/admin/dataStatistics")
    public String dataStatistics(Model model) throws JsonProcessingException {

        // 最近7天用户增长数据
        List<Myuser> users = myuserService.list();
        LocalDate today = LocalDate.now();
        Map<String, Long> recentUserGrowthMap = users.stream()
                .filter(user -> user.getCreateTime().toLocalDate().isAfter(today.minusDays(7)))
                .collect(Collectors.groupingBy(
                        user -> user.getCreateTime().toLocalDate().toString(),
                        Collectors.counting()
                ));
        List<Map<String, Object>> recentUserGrowthData = new ArrayList<>();
        for (Map.Entry<String, Long> entry : recentUserGrowthMap.entrySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("date", entry.getKey());
            map.put("count", entry.getValue());
            recentUserGrowthData.add(map);
        }
        model.addAttribute("userGrowthData", JSON.toJSONString(recentUserGrowthData));
        // 产品分类数据
        List<Goods> goods = goodsService.list();
        goods.forEach(goods1 -> {
            goods1.setTypename(String.valueOf(goodstypeService.lambdaQuery().eq(Goodstype::getId, goods1.getGoodstypeId()).one().getTypename()));
        });
        Map<String, Long> productCategoryMap = goods.stream()
                .collect(Collectors.groupingBy(Goods::getTypename, Collectors.counting()));
        List<Map<String, Object>> productCategoryData = new ArrayList<>();
        for (Map.Entry<String, Long> entry : productCategoryMap.entrySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("category", entry.getKey());
            map.put("count", entry.getValue());
            productCategoryData.add(map);
        }
        model.addAttribute("productCategoryData", JSON.toJSONString(productCategoryData));

        // 销售比例数据
        List<OrderDetail> orderDetails = orderDetailService.list();
        Map<String, Double> salesMap = orderDetails.stream()
                .collect(Collectors.groupingBy(
                        od -> {
                            Goods goods_temp = goodsService.getById(od.getGoodsid());
                            return goods_temp != null ? goods_temp.getName() : "未知商品";
                        },
                        Collectors.summingDouble(od -> {
                            Goods goods_temp = goodsService.getById(od.getGoodsid());
                            return goods_temp != null ? od.getBuyNum() * goods_temp.getPrice() : 0.0;
                        })
                ));
        List<Map<String, Object>> salesData = new ArrayList<>();
        for (Map.Entry<String, Double> entry : salesMap.entrySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", entry.getKey());
            map.put("totalSales", entry.getValue());
            salesData.add(map);
        }
        model.addAttribute("salesData", JSON.toJSONString(salesData));
        // 订单状态数据
        List<Myorder> orders = myorderService.list();
        Map<Integer, Long> orderStatusMap = orders.stream()
                .collect(Collectors.groupingBy(Myorder::getStatus, Collectors.counting()));

        List<Map<String, Object>> orderStatusData = new ArrayList<>();
        for (Map.Entry<Integer, Long> entry : orderStatusMap.entrySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("status", String.valueOf(entry.getKey())); // 将 Integer 转换为 String
            map.put("count", entry.getValue());
            orderStatusData.add(map);
        }
        model.addAttribute("orderStatusData", JSON.toJSONString(orderStatusData));
        return "/pages/dataStatistics";
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查是否有用户信息存储在session中
        Myuser user = (Myuser) request.getSession().getAttribute("user");
        if (user != null) {
            // 如果用户已登录，放行
            return true;
        } else {
            // 如果用户未登录，重定向到登录页面
            request.getSession().setAttribute("msg", "请先登录!!");
            response.sendRedirect("/admin/login");
            return false;
        }
    }


}
